package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.exception.BaseException;
import com.atguigu.spzx.manager.mapper.SysMenuMapper;
import com.atguigu.spzx.manager.service.ISysMenuService;
import com.atguigu.spzx.model.vo.common.entity.system.SysMenu;
import com.atguigu.util.RegularizationMenuUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author 宋哥
 * @since 2024-01-12
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 添加菜单
     * @param sysMenu
     */
    public void addMenu(SysMenu sysMenu) {
         save(sysMenu);
    }

    /**
     * 查询树形菜单
     * @return
     */
    public List<SysMenu> findMenus() {
        List<SysMenu> sysMenuList= sysMenuMapper.finndAllMenus();
        //将获取到的节点树形化
        return RegularizationMenuUtil.getRegularMenu(sysMenuList);
    }

    /**
     * 根据id修改菜单
     * @param sysMenu
     */
    public void updateMenu(SysMenu sysMenu) {
        boolean b = updateById(sysMenu);
        if(!b){
            throw new BaseException("修改失败");
        }
    }

    /**
     * 根据id删除菜单
     * @param menuId
     */
    public void deleteMenuById(Long menuId) {
        //查询当前菜单下是否存在子菜单
        Long count = sysMenuMapper
                .selectCount(new LambdaQueryWrapper<SysMenu>()
                        .eq(menuId != null, SysMenu::getParentId, menuId));
        if(count>0){
            //存在子菜单
            throw new BaseException("删除失败,当前菜单存在子菜单");
        }
        boolean isSuccess = removeById(menuId);
        if(!isSuccess){
            throw new BaseException("删除失败");
        }
    }

}
